﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.Sales
{
	public partial class CashReceiptChoice : Form
	{	public	int? CashRegisterShiftId{get{return cashRegisterShiftId;}}
		private	int? cashRegisterShiftId = null;

		public	int DocId{get{return currentRow != null? currentRow.Id: 0;}}
		public	DateTime DocDate{get{return currentRow != null? currentRow.DocDate: DateTime.MinValue;}}
		public	string DocNumber{get{return currentRow != null? currentRow.DocNumber: string.Empty;}}

		private	DIProject.DataSets.Sales.CashRegistersCanReturnRow currentRow = null;
//-------------------------------------------------------------------------------------------------
		public CashReceiptChoice() : this(null)
		{
		}

		public CashReceiptChoice(int? cashRegisterShiftId)
		{	InitializeComponent();
			this.cashRegisterShiftId = cashRegisterShiftId;
		}
//-------------------------------------------------------------------------------------------------
		private void CashReceiptChoice_Load(object sender, EventArgs e)
		{	try
			{	cashRegistersCanReturnTableAdapter.Fill(sales.CashRegistersCanReturn, CashRegisterShiftId);
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
//-------------------------------------------------------------------------------------------------
		private void cashRegisters_CurrentCellChanged(object sender, EventArgs e)
		{	if(cashRegisters.CurrentCell != null)
			{	buttonAccept.Enabled = true;
				currentRow = (DIProject.DataSets.Sales.CashRegistersCanReturnRow)((DataRowView)cashRegisters.CurrentCell.OwningRow.DataBoundItem).Row;
			}
			else
			{	buttonAccept.Enabled = false;
				currentRow = null;
			}
		}
//-------------------------------------------------------------------------------------------------
		private void cashRegisters_MouseDoubleClick(object sender, MouseEventArgs e)
		{	DataGridView.HitTestInfo hit = cashRegisters.HitTest(e.X, e.Y);
			if(hit.RowIndex >= 0)
			{	DialogResult = DialogResult.OK;
				Close();
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		List<char> keys = new List<char>();
		Util.PerfCounter totalCounter = new Util.PerfCounter();
		Util.PerfCounter keyPressCounter = new Util.PerfCounter();
//-------------------------------------------------------------------------------------------------
		private void cashRegisters_KeyDown(object sender, KeyEventArgs e)
		{	if(e.KeyCode == Keys.Enter)
				e.Handled = true;
		}
//-------------------------------------------------------------------------------------------------
		private void cashRegisters_KeyPress(object sender, KeyPressEventArgs e)
		{	double keyPressSecs = keyPressCounter.Running? keyPressCounter.Finish(): 0;
			if(!totalCounter.Running)
				totalCounter.Start();
			double totalSecs = totalCounter.State();
			if(keyPressSecs > Util.PerfCounter.BarcodeScannerKeyPressMaxDelay)
			{	keys.Clear();
				totalCounter.Start();
			}
			keys.Add(e.KeyChar);
			if(e.KeyChar == '\r')
			{	if(totalSecs < Util.PerfCounter.BarcodeScannerTotalMaxDelay)	// Сканер штрих-кодов
				{	if(keys.Count >= 12)
					{	keys.RemoveAt(keys.Count - 2);	// отрезаем контрольную цифру (-2, т.к. последний - '\r')
						int cashCheckId;
						try
						{	cashCheckId = BitConverter.ToInt32(BitConverter.GetBytes(uint.Parse(new string(keys.ToArray()))), 0);
							currentRow = sales.CashRegistersCanReturn.FindById(cashCheckId);
							if(currentRow != null)
							{	DialogResult = DialogResult.OK;
								Close();
								return;
							}
						}
						catch
						{
						}
					}
					Console.Beep();
				}
				else if(cashRegisters.CurrentCell != null)	// Ручной ввод и есть выделенная ячейка
				{	DialogResult = DialogResult.OK;
					Close();
				}
				keys.Clear();
				totalCounter.Finish();
			}
			keyPressCounter.Start();
        }
//-------------------------------------------------------------------------------------------------
	}
}